package com.qidian.buy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qidian.buy.mapper.ContentCategoryMapper;
import com.qidian.buy.mapper.ContentMapper;
import com.qidian.buy.pojo.Content;
import com.qidian.buy.pojo.ContentCategory;
import com.qidian.buy.service.ContentCategoryService;
import com.qidian.buy.service.ContentService;
import com.qidian.buy.util.JSONTools;
import com.qidian.buy.util.QdConstant;
import com.qidian.buy.util.ThreadPoolUtil;
import com.qidian.buy.util.pojo.QdResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author 戴着假发的程序员
 * @company 起点编程
 * @date 2023/9/6 10:58
 */
@Service
@RefreshScope
public class ContentServiceImpl implements ContentService {
    @Value("${indexMarks}")
    private String indexMarks;
    @Autowired
    private ContentMapper contentMapper;
    @Autowired
    private ContentCategoryMapper categoryMapper;
    @Autowired
    private ThreadPoolUtil threadPoolUtil;

    // redis的工具类对象
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public QdResult queryIndexData() {
        // 准备一个Map
        Map<String,List<Content>> result = new HashMap<>();
        // 遍历indexMarks，循环的查询
        for (String mark : indexMarks.split(",")){
            List<Content> contents = null;
            // 现查询缓存
            String key = "CONTENT_"+mark;
            if(redisTemplate.hasKey(key)){
                // 缓存中有数据
                String contentJson = redisTemplate.opsForValue().get(key);
                // 将json转换为集合对象
                try {
                    contents = JSONTools.json2list(contentJson,Content.class);
                } catch (Exception e) {
                    // 这里只是做一个纪录
                    throw new RuntimeException(e);
                }
            }
            if(contents == null) {// 说明redis中没有数据
                // 从数据库查询
                contents =  contentMapper.queryByCatMark(mark);
                // 给redis存储一份
                redisTemplate.opsForValue().set(key,JSONTools.object2json(contents));
                // 设置缓存的时间
                redisTemplate.expire(key,60+(new Random().nextInt(30)), TimeUnit.MINUTES);
            }
            // 将数据放入map
            result.put(mark,contents);
        }
        // 将map放入qdResult返回
        return QdResult.ok(result);
    }

    @Override
    public QdResult save(Content content) {
        // 查询mark
        ContentCategory category = categoryMapper.selectById(content.getCatId());
        // 先删除缓存
        String key = "CONTENT_" + category.getCatMark();
        redisTemplate.delete(key);
        content.setCreateTime(new Date());
        content.setModifyTime(new Date());
        content.setStatus(1);
        int result = contentMapper.insert(content);
        // 启动一个子线程再次删除缓存
        // 获取线程池
        ThreadPoolExecutor executor = threadPoolUtil.get("synchronousCache", 3);
        // 提交一个任务
        executor.execute(()->{
            try {
                // 使用循环是防止删除失败的重试机制
                while(redisTemplate.hasKey(key)) {
                    // 等待500毫秒之后再次删除
                    Thread.sleep(500);
                    // 再次删除
                    boolean deleteResult = redisTemplate.delete(key);
                    if (deleteResult) {
                        break;
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        return QdResult.isOk(result);
    }

    @Override
    public QdResult queryByCatMark(String catMark, int pageNum, int limit) {
        QueryWrapper<Content> wrapper = new QueryWrapper<>();
        wrapper.ne("status",QdConstant.DATA_DELETED);
        IPage<Content> page = new Page<>(pageNum,limit);
        return QdResult.ok(contentMapper.selectList(page,wrapper));
    }

    @Override
    public QdResult queryByCatId(Long catId, int pageNum, int limit) {
        QueryWrapper<Content> wrapper = new QueryWrapper<>();
        wrapper.ne("status", QdConstant.DATA_DELETED);
        wrapper.eq("cat_id",catId);
        IPage<Content> page = new Page<>(pageNum,limit);
        return QdResult.ok(contentMapper.selectList(page,wrapper));
    }

    @Override
    public QdResult queryById(Long contentId) {
        return QdResult.ok(contentMapper.selectById(contentId));
    }

    @Override
    public QdResult update(Content content) {
        content.setModifyTime(new Date());
        return QdResult.ok(contentMapper.updateById(content));
    }

    @Override
    public QdResult delete(Content content) {
        content.setStatus(QdConstant.DATA_DELETED);
        return QdResult.ok(contentMapper.updateById(content));
    }

    @Override
    public QdResult list(Content content, int pageNum, int limit) {
        IPage<Content> page = new Page<>(pageNum,limit);
        return QdResult.ok(contentMapper.queryByPage(page,content));
    }
}
